package com.xwtec.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zt
 * @Date: 2021/3/1 21:49
 *
 * 组合模式，专为树状模式使用
 */
public class Main {
    public static void main(String[] args) {
        BranchNode root = new BranchNode("root");
        BranchNode charset1 = new BranchNode("charset1");
        BranchNode charset2 = new BranchNode("charset2");

        LeafNode c11 = new LeafNode("c11");
        LeafNode c12 = new LeafNode("c12");
        BranchNode session21 = new BranchNode("session21");
        LeafNode s211 = new LeafNode("s211");
        LeafNode s212 = new LeafNode("s212");
        root.add(charset1);
        root.add(charset2);
        charset1.add(c11);
        charset1.add(c12);
        charset2.add(session21);
        session21.add(s211);
        session21.add(s212);
        tree(root,0);

    }
    static void tree(Node node,int depth){
        for (int i = 0; i <depth ; i++) {
            System.out.print("--");
        }
        node.p();

        if(node instanceof BranchNode){
            depth++;
            for (Node e:((BranchNode) node).nodeList) {

                tree(e,depth);
            }

        }
    }

}

abstract class Node{
    abstract void p();
}


//叶子节点
class LeafNode extends Node{
    String content;

    public LeafNode(String content) {
        this.content = content;
    }

    @Override
    void p() {
        System.out.println(content);
    }
}
//支节点
class BranchNode extends Node{

    String name;

   List<Node> nodeList = new ArrayList<Node>();

    public BranchNode(String name) {
        this.name = name;
    }
    public void add(Node e){
        nodeList.add(e);
    }

    @Override
    void p() {
        System.out.println(name);
    }
}